package com.yl.common.utils;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * Created by cjx on 2020-03-05
 * 说明：
 */
public class CacheFileUtil {

    private static volatile CacheFileUtil util;

    public static CacheFileUtil getInstance() {
        if (util == null) {
            synchronized (CacheFileUtil.class) {
                if (util == null) {
                    util = new CacheFileUtil();
                }
            }
        }
        return util;
    }

    private CacheFileUtil() {
    }

    private void makeDir(String dir) {
        File file = new File(dir);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    public void saveCacheInfoAes(String dir, String info, String name, String pwd) {
        makeDir(dir);
        String encrypt = AESUtils.encrypt(info, pwd);
        saveCacheInfo(dir, encrypt, name);
    }

    public void saveCacheInfo(String dir, String info, String name) {
        makeDir(dir);
        File file = new File(dir, name);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file, false);
            byte[] bytes = info.getBytes(StandardCharsets.UTF_8);
            fileOutputStream.write(bytes);
            fileOutputStream.flush();
            try {
                FileDescriptor fd = fileOutputStream.getFD();
                fd.sync();
            }catch (Exception e){}
            fileOutputStream.close();
        } catch (
                FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String readCacheInfoAes(String dir, String name, String pwd) {
        return AESUtils.decrypt(readCacheInfo(dir, name), pwd);
    }

    public String readCacheInfo(String dir, String name) {
        String cache;
        // 打开文件输入流
        try {
            File file = new File(dir, name);
            if (!file.exists()) {
                return null;
            }
            FileInputStream fileInputStream = new FileInputStream(file);
            int available = fileInputStream.available();
            byte[] buffer = new byte[available];
            fileInputStream.read(buffer);
            // 关闭输入流
            fileInputStream.close();
            cache = new String(buffer, StandardCharsets.UTF_8);
        } catch (Exception e) {
            cache = null;
        }
        return cache;
    }

}
